import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { User } from '@/views/users/UserListView.vue'

export const useUserStore = defineStore('user', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  const userList = ref<User[]>([
    {
      username: "admin",
      name: "mark21",
      gender: "男",
      department: "编辑部",
      email: "",
      phone: "123456789",
      status: "激活",
      id: 1001,
    },
    {
      username: "admin",
      name: "mark21",
      gender: "男",
      department: "编辑部",
      email: "",
      phone: "123456789",
      status: "激活",
      id: 1002,
    },
    {
      username: "admin",
      name: "mark21",
      gender: "男",
      department: "编辑部",
      email: "",
      phone: "123456789",
      status: "激活",
      id: 1003,
    },
    {
      username: "admin",
      name: "mark21",
      gender: "男",
      department: "编辑部",
      email: "",
      phone: "123456789",
      status: "激活",
      id: 1004,
    },
  ]);

  const user = ref<User>()

  const addUser = (user:User) => {
    userList.value.push({...user, id: _createId()})
  }

  const deleteUser = (userId: number) => {
    const index = userList.value.findIndex(user => user.id === userId);
    console.log(userList.value);
    
    if (index !== -1) {
      userList.value.splice(index, 1);
    }
  }

  const findUser = (userId: number) => {
    const index = userList.value.findIndex(user => user.id === userId);
    console.log(userList.value[index], 555555555);
    
    user.value = userList.value[index]
  }

  const _createId = () => {
    return userList.value.length > 0 
      ? Math.max(...userList.value.map(user => user.id)) + 1 
      : 1;
  }

  return { count, doubleCount, increment, userList, addUser, deleteUser, findUser, user }
})
